package com.zrrd.yt.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.zrrd.yt.common.result.Result;
import com.zrrd.yt.common.util.IpUtil;
import com.zrrd.yt.model.user.UserInfo;
import com.zrrd.yt.service.constant.RedisConst;
import com.zrrd.yt.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author HongyueYang
 */
@RestController
@RequestMapping("/api/user/passport")
public class UserApiController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    //登录
    @PostMapping("login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request){
        //调用业务层
        UserInfo user = userInfoService.login(userInfo);
        //判断是否存在
        if (user != null){
           //使用uuid生成一串随机内容当中token
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            //创建给前端返回的Map集合对象
            Map<String,Object> map = new HashMap<>();
            map.put("nickName",user.getNickName());
            map.put("token",token);

            //创建JSON对象 保存userid和ip信息
            JSONObject userJson = new JSONObject();
            userJson.put("userId",user.getId().toString());
            userJson.put("ip", IpUtil.getIpAddress(request));

            //把token作为key userId和ip作为value放入redis
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX+token,
                    userJson.toJSONString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);

            //返回
            return Result.ok(map);
        }else {
            return Result.fail().message("用户名或密码错误");
        }
    }

    //退出登录处理
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX+request.getHeader("token"));
        return Result.ok();
    }
}
